//
//  CompoundGoodsList.swift
//  LeGou
//
//  Created by lxm on 2022/11/10.
//

import UIKit

class CompoundGoodsList: ZMViewController, UITableViewDelegate, UITableViewDataSource {

    //MARK:--------------------属性--------------------
    // ("合成中", 0), ("已合成", 1), ("已失效", 2)
    var type = 0
    
    var rewardStr = ZMUtil.fastBehavior(value: "")
    
    var conflateId = 0
    var listData = [ListModel]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    
    var maxCount = 10
    
    var listchangeCallBack : (()->())?
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var tipsContent: UIView!
    
    @IBOutlet weak var tipsLabel: UILabel!
    
    @IBOutlet weak var compoundBtn: UIButton!
    
    let loading = XMLoadingView()
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        tableView.mj_header?.beginRefreshing()
    }
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "合成详情"
        tableView.delegate = self
        tableView.dataSource = self
        tableView.zm.register(nibName: "CompoundGoodsListCell", reuserId: "CompoundGoodsListCell")
        tableView.estimatedRowHeight = 156
        tableView.rowHeight = UITableView.automaticDimension
        tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
        
        addRefresh(scrollView: tableView, addFoot: false) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        rewardStr.subscribe(onNext:{ [unowned self] resp in
            self.tipsContent.isHidden = resp.count == 0
            self.tipsLabel.text = resp
        }).disposed(by: disposeBag)
    }

    func loadList() {
        if type == 0 {
            let pa = ["limit" : pageSize, "page" : page, "conflateId" : conflateId] as [String : Any]
            AuctionAPI.compoundDetailOngoingList(pa).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                self.loading.hideView(anmation: true)
                self.listData.removeAll()
                if let arrayd = resp["conflateDetailListResponseList"] as? [[String : Any]] {
                    if let r = [ListModel].deserialize(from: arrayd){
                        self.listData = r.compactMap({$0})
                    }
                }
                if let s = resp["rewardStr"] as? String {
                    self.rewardStr.accept(s)
                }
                self.tableView.reloadData()
                self.tableView.mj_header?.endRefreshing()
                
                let ok = self.listData.count >= self.maxCount
                self.compoundBtn.backgroundColor = ok ? Style.mainColor : Style.disableColor
                self.compoundBtn.isEnabled = ok
            }, onError: { e in
                self.loading.showError(e.localizedDescription)
            }).disposed(by: disposeBag)
        }
    }
    
    
    //MARK:--------------------delegate--------------------
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CompoundGoodsListCell") as! CompoundGoodsListCell
        cell.setStytle(s: indexPath.row % 3)
        let data = listData[indexPath.row]
        cell.img.zm.setImage(urlStr: data.image)
        cell.name.text = data.productName
        cell.dateNum.text = "第\(data.ahCount)期"
        cell.price.attributedText = "".zm.append(str: "¥", attri: ["f" : Style.FONT_Open_Sans_SemiBold(12)]).zm.append(str: data.currentPrice.zm.toString(keep: 4))
        if data.state == 1 {
            // 审核中
            cell.setStytle(s: 2)
        } else if data.stockState == 1 {
            // 缺货
            cell.setStytle(s: 1)
            cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.onExchangeIntegarl(m: data)
            }).disposed(by: cell.disposeBag)
        } else {
            cell.setStytle(s: 0)
            cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.onExchangeIntegarl(m: data)
            }).disposed(by: cell.disposeBag)
            
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.onSend(m: data)
            }).disposed(by: cell.disposeBag)
        }
        
        
        
        return cell
    }
    
    // 兑换积分
    func onExchangeIntegarl(m : ListModel) {
        ZMAlertView.show(title: "提示", content: "是否确认兑换积分?", left: "取消", right: "确认") {
            
        } onRight: {
            AuctionAPI.exchangeIntegral(["orderId" : m.orderId]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
                self.tableView.mj_header?.beginRefreshing()
                if let listchangeCallBack = self.listchangeCallBack {
                    listchangeCallBack()
                }
            }).disposed(by: self.disposeBag)
        }
    }
    
    // 发货
    func onSend(m : ListModel) {
        let vc = ZMAddressListVC()
        vc.chooseAddressBlockNopush = { [unowned self] address in
            ZMAlertView.show(title: "提示", content: "您是否确认选择该收货地址提交平台审核？", left: "取消", right: "确认") {
                
            } onRight: {
                self.navigationController?.popViewController(animated: true)
                self.deliver(address: address, m: m)
                
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func deliver(address : AddressModel, m : ListModel) {
        AuctionAPI.applySend(["addressId" : address.id, "orderId" : m.orderId]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
            self.tableView.mj_header?.beginRefreshing()
        }).disposed(by: disposeBag)
    }
    
    @IBAction func onCompound(_ sender: Any) {
        compound(conflateId : conflateId)
    }
    
    // 合成
    func compound(conflateId : Int) {
        ZMToast.showActivity()
        AuctionAPI.compound(["conflateId" : conflateId]).rxRequest(type: AuctionModels.CompoundResult.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            if resp.giveQuantity == 0 {
                // 无商品
                let v = ZMUtil.loadNibViewFullScreen(nibName: CompoundSuccessNoGoodsView.self)
                v.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "14s"]).zm.append(str: "\(resp.rewardAmount.zm.toString(keep: 4))")
                v.sureBtn.rx.tap.subscribe(onNext:{ [unowned self, weak v] r in
                    if let listchangeCallBack = self.listchangeCallBack {
                        listchangeCallBack()
                    }
                    self.navigationController?.popViewController(animated: true)
                    v?.removeFromSuperview()
                }).disposed(by: v.disposeBag)
                APPWindow?.addSubview(v)
            } else {
                let v = ZMUtil.loadNibViewFullScreen(nibName: CompoundSuccessView.self)
                v.count.text = "\(resp.giveQuantity)"
                v.price.attributedText = "".zm.append(str: "¥", attri: ["f" : "14s"]).zm.append(str: "\(resp.rewardAmount.zm.toString(keep: 4))")
                v.sureBtn.rx.tap.subscribe(onNext:{ [unowned self, weak v] r in
                    let vc = VIPOrderDetail()
                    vc.orderNo = resp.orderId
                    self.replace(vc)
                    if let listchangeCallBack = self.listchangeCallBack {
                        listchangeCallBack()
                    }
                    v?.removeFromSuperview()
                }).disposed(by: v.disposeBag)
                APPWindow?.addSubview(v)
            }
        }).disposed(by: disposeBag)
    }
    
    func goDetail(m : AuctionModels.CompoundResult) {
        let vc = CompoundOrderDetail()
//        vc.orderNo =
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let vc = CompoundOrderDetail()
//        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension CompoundGoodsList {
    class ListModel  : HandyJSON {
        required init(){}
        var ahCount: Int = 0
        var auctionId: Int = 0
        var conflateId: Int = 0
        var conflateRefundStatus: Int = 0
        var currentPrice = 0.0
        var image = ""
        var oid: Int = 0
        var orderId = ""
        var productName = ""
        var stockState: Int = 0
        // 是否申请发货，处于审核中：0否 1是(置灰申请发货、兑换积分按钮)
        var state = 0
    }
}
